import logging
from opslog.cli import api

class Client(object):
    def __init__(self, server, args):
        self.server = server
        self.args = args
        self.logger = logging.getLogger()
 
    def process_error(self, response):
        if response.has_key("error"):
            if response["error"] == "noaccount":
                self.init_account()
            elif response["error"] == "connection_refused":
                self.logger.error("Server unreachable")
            else:
                self.logger.error("Unknown server error %s:%s" % (response["error"], response["description"]))
        else:
            self.logger.error("Unknown server error")
    
    def auth_setup(self):
        self.server.setup()
    
    def auth_check(self):
        response = False
        try:
            response = getattr(self.server,"ping")()
        except api.InteractiveAuthRequired:
            response = False
        else:
            response = True
        return response
 
    def server_call(self,method,*args,**kwargs):
        response = None
        if hasattr(self.server,method):
            try:
                response = getattr(self.server,method)(*args,**kwargs)
            except api.InteractiveAuthRequired:
                if self.auth_setup():
                    self.server_call(method,*args,**kwargs)
        return response
    
